<template>
  <el-dialog :visible.sync="dialogVisible" width="80%" @closed="dialogClosed">
    <el-form ref="searchForm" :inline="true" :model="search" :rules="rules">
      <el-form-item label="项目名称" prop="sysCode">
        <el-select v-model="search.sysCode" @change="getGroupList">
          <el-option v-for="item in sysList" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务名称" prop="groupCode">
        <el-select v-model="search.groupCode" @change="$forceUpdate()"><el-option v-for="item in groupList" :key="item.code" :label="item.name" :value="item.code"></el-option></el-select>
      </el-form-item>
      <el-form-item label="交易码" prop="transCode"><el-input v-model="search.transCode" :maxlength="20" show-word-limit></el-input></el-form-item>
      <el-form-item><el-button type="primary" icon="el-icon-search" @click="searchTree">查询</el-button></el-form-item>
    </el-form>

    <el-row type="flex" justify="space-between">
      <el-col :span="10">
        <el-card shadow="hover" class="slot-header">
          <div slot="header">
            <i class="el-icon-setting"></i>
            执行流程
          </div>
          <template v-if="data && data.length">
            <div class="card-content"><menu-tree :data="data" ref="treemenu" :getAddList="getAddList" :allowDrop="allowDrop" @handlerClick="handlerClick" /></div>
            <el-button type="primary" icon="el-icon-document-checked" class="save-btn" @click="saveFlow">保存流程</el-button>
          </template>
        </el-card>
      </el-col>

      <el-col :span="13">
        <el-card shadow="hover" class="slot-header">
          <div slot="header">
            <i class="el-icon-box"></i>
            流程节点信息
          </div>
          <template v-if="formList && formList.length">
            <div class="card-content">
              <el-form label-width="100px">
                <el-form-item label="节点类型" required><el-input disabled v-model="targetData.label"></el-input></el-form-item>
              </el-form>
              <el-form ref="dataForm" label-width="100px" :model="formData">
                <el-form-item v-for="(item, index) in formList" :key="index" :label="item.label" :rules="item.rules" :prop="item.key">
                  <el-select v-if="item.type === 'select'" v-model="formData[item.key]" @change="((val) => {formSelect(val,item)})">
                    <el-option v-for="option in getDicData(item.dicDataKey)" :key="option[item.dicOptionKey]" :value="option[item.dicOptionKey]" :label="option.name"></el-option>
                  </el-select>
                  <el-input v-else v-model="formData[item.key]" :maxlength="item.maxlength" :show-word-limit="item.showWordLimit"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <el-button type="primary" icon="el-icon-circle-check" class="save-btn" @click="saveInfo">保存节点信息</el-button>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { createTree, addObj,putObj,delObj,getNacosServers } from '@/api/pre/process'
import MenuTree from '@/components/menu-tree/main'
import { getSysList } from '@/api/pre/insystem'
import { getGroupList,groupCodeAndOut,getGroupListBySysCode } from '@/api/pre/group'
import { addList, formMap } from './config'
import _cloneDeep from 'lodash/cloneDeep'
import _isEmpty from 'lodash/isEmpty'

export default {
  name: 'ProcessDetail',
  components: {
    MenuTree
  },
  props: {
    visible: {
      type: Boolean,
      default() {
        return false
      }
    },
    searchData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      // 当弹窗打开，且有传入数据时，获取分组名称，并创建树结构
      if (this.visible && !_isEmpty(this.searchData)) {
        this.search = _cloneDeep(this.searchData)
        this.getGroupList(this.searchData.sysCode,true).then(() => {
          this.searchTree()
        })
        this.groupCodeAndOut()
      }
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      search: {
        sysId: '',
        sysCode: '',
        groupCode: '',
        transCode: ''
      },
      sysList: [],
      groupList: [],
      servicesList:[],
      methodTypeList:[{code:"GET"},{code:"POST"}],
      groupAndOutList: [],
      rules: {
        sysCode: [{ required: true, message: '项目名称不能为空' }],
        groupCode: [{ required: true, message: '服务名称不能为空' }],
        transCode: [{ required: true, message: '交易码不能为空', trigger: 'blur' }]
      },
      data: [],
      targetData: {},
      formList: [],
      formData: {},
      addList: null
    }
  },
  created() {
    this.getSysList();
    this.getServicesList();
  },
  methods: {
    getSysList() {
      getSysList().then(res => {
        this.sysList = res.data.data
      })
    },
    getServicesList(){
      getNacosServers().then(res=>{
        console.log("nacos list==",res)
        if(res.data.code=='0'){
          var list=res.data.data;
          list.forEach(svr=> {
            this.servicesList.push({code:svr})});
          }
       });
    },
    getGroupList(value,flag) {
      return getGroupListBySysCode(value).then(res => {
        this.groupList = res.data.data
        if (this.groupList.length) {
          if (!flag) this.search.groupCode = this.groupList[0].code
        }else{
          this.search.groupCode = ""
        }
      })
    },
    groupCodeAndOut(){
      groupCodeAndOut(this.search.sysCode).then(res => {
        this.groupAndOutList = res.data.data
      })
    },
    // 获取数结构
    searchTree() {
      this.$refs.searchForm.validate(valid => {
        if (!valid) {
          return
        }
		this.groupCodeAndOut()

        createTree(this.search).then(res => {
          if(res.data.data == null){
            this.searchData.flowId = null
            this.data = [{
              "id": 0,
              "label": this.search.sysCode + "." + this.search.groupCode + "." + this.search.transCode + "." + "流程配置",
              "children": [{
                "id": 3,
                "label": "解包报文",
                "children": [],
                "dataModel": {
                  "systemId": this.search.sysCode,
                  "group": this.search.groupCode,
                  "inParam": "",
                  "outParam": "",
                  "transCode": this.search.transCode,
                  "recvField": null,
                  "inDict": null,
                  "type": "UNPACK"
                },
                "dropInner": false,
                "type": "UNPACK",
              }, {
                "id": 9,
                "label": "YFA调用",
                "children": [],
                "dataModel": {
                  "group": this.search.groupCode,
                  "inParam": "",
                  "outParam": "",
                  "transCode": this.search.transCode,
                  "type": "SNDYFA"
                },
                "dropInner": false,
                "type": "SNDYFA",
              }, {
                "id": 4,
                "label": "报文组包",
                "children": [],
                "dataModel": {
                  "systemId": this.search.sysCode,
                  "group": this.search.groupCode,
                  "inParam": "",
                  "outParam": "",
                  "transCode": this.search.transCode,
                  "recvField": null,
                  "inDict": null,
                  "type": "PACK"
                },
                "dropInner": false,
                "type": "PACK",
              }, {
                "id": 5,
                "label": "发送报文",
                "children": [],
                "dataModel": {
                  "systemId": this.search.sysCode,
                  "group": this.search.groupCode,
                  "inParam": "",
                  "outParam": "",
                  "transCode": this.search.transCode,
                  "recvField": "",
                  "inDict": "",
                  "type": "SEND"
                },
                "dropInner": false,
                "type": "SEND",
              }],
              "dropInner": true,
              "root": false,
              "type": null
            }]
          }else{
            // this.data = _cloneDeep(res.data.data)
            this.data = []
            this.searchData.flowId = res.data.data.flowId
            this.data.push(res.data.data.content)
          }
        })
      })
    },
    // 弹窗关闭时的处理
    dialogClosed() {
      this.$refs.searchForm.resetFields()
      this.$emit('update:visible', false)

      this.search = {}
      this.data = []
      this.formList = []
      this.targetData = {}
    },
    // 获取addList
    getAddList(data, node) {
      if (!this.addList) {
        // 对this.addList进行初始化赋值，尤其是dataModel的赋值
        const defaultKey = ['systemId', 'group', 'transCode']
        this.addList = addList.map(addItem => {
          const dataModel = {
            type: addItem.value
          }
          formMap[addItem.value].forEach(item => {
            // if (defaultKey.indexOf(item.key) > -1) {
            //   dataModel[item.key] = this.search[item.key]
            //   return
            // }
            dataModel[item.key] = ''
            if (addItem.value === 'EXTCALL') return false;
            if (item.key == 'systemId') dataModel.systemId = this.search.sysCode
            if (item.key == 'group') dataModel.group = this.search.groupCode
            if (item.key == 'transCode') dataModel.transCode = this.search.transCode
          })

          return {
            label: addItem.label,
            type: addItem.value,
            value: addItem.value,
            dataModel
          }
        })
      }
      // 若addList已赋值，则直接返回
      return this.addList
    },
    allowDrop(draggingNode, dropNode, type) {
      // 根节点，只能放置为子节点
      if (dropNode.data.root) {
        return type === 'inner'
      }
      return true
    },
    // 获取字典内容
    getDicData(key) {
      return this[key]
    },
    checkWarning() {
      if (!this.targetData.dataModel) {
        return false
      }

      const value = this.targetData.value
      if (value && value !== 'save') {
        // 若为后期添加的节点，且未保存过，直接返回warning
        return true
      }

      // 初始化就存在的节点，或者是保存过的节点，则直接判断前后的数据是否一致
      const diff = JSON.stringify(this.targetData.dataModel) !== JSON.stringify(this.formData)
      this.targetData.formData = this.formData
      // 若不一致，直接warning。若一致，后期添加的节点返回success，初始化存在的节点返回null
      this.$set(this.targetData, 'status', diff ? 'warning' : value ? 'success' : null)
      return diff
    },
    //选择右边框系统分组
    formSelect(val,item){
      if (item.key !== 'group') return false;
      let sysFlag = this.getDicData("groupAndOutList").find( (item) => item.code == val).flag
      if (sysFlag === 'inSys'){
        this.formData.systemId = ''
      }else{
        this.formData.systemId = this.search.sysCode
      }
    },
    // 点击树结构节点时的处理
    handlerClick(data) {
      this.checkWarning()

      if (data.root || !data.dataModel) {
        this.formList = []
        return
      }

      // 获取当前节点的dataModel，渲染form
      const dataModel = data.dataModel
      const list = []

      formMap[data.type].forEach(item => {
        const value = data.dataModel[item.key]
        // value为null时，不渲染
        if (value !== null) {
          list.push(item)
        }
      })
      this.targetData = data
      this.formList = list
      if (!data.formData) {
        data.formData = _cloneDeep(dataModel)
      }
      this.formData = data.formData
    },
    saveInfo() {
      this.$refs.dataForm.validate(valid => {
        if (!valid) {
          return
        }

        // TODO 请求接口保存当前节点信息
        this.$set(this.targetData, 'status', 'success') // 成功时为success，失败时为error
        this.targetData.dataModel = _cloneDeep(this.formData)
        if (this.targetData.value) {
          // 若是后期添加的节点，则有value属性，保存后，将value属性的值改为save
          this.targetData.value = 'save'
        }
        this.$message.success('节点信息保存成功！')
      })
    },
    saveFlow() {
      if (this.checkWarning()) {
        this.$message.error('请先保存节点信息')
        return
      }
      // 递归检查this.data是否有status为warning或者error的状态
      const checkError = arr => {
        return arr.some(item => {
          if (item.status === 'warning' || item.status === 'error') {
            return true
          }
          if (item.children && item.children.length) {
            return checkError(item.children)
          }
        })
      }

      if (checkError(this.data)) {
        this.$message.error('请先保存节点信息')
        return
      }
      let param = {
            systemCode: this.search.sysCode,
            groupCode: this.search.groupCode,
            transCode: this.search.transCode,
            data: this.data[0],
            flowId: this.searchData.flowId
          }
      if(param.flowId == null){
        addObj(param).then(response => {
          this.$message.success('流程保存成功！')
          this.$emit('update')
          this.dialogVisible = false
        })
      }else{
        putObj(param).then(response => {
          this.$message.success('流程更新成功！')
          this.$emit('update')
          this.dialogVisible = false
        })
      }
      // TODO 请求保存流程接口
      // this.$message.success('流程保存成功！')
      // this.dialogVisible = false
    }
  }
}
</script>

<style></style>
